<?php

namespace App\Services\Admin;

use App\Services\Service;
use App\Models\Role;

class RoleService extends Service
{
    public static function options(): array
    {
        $list = Role::orderBy('sort', 'asc')->select('id', 'name')->get()->toArray();

        $list = array_map(fn($item) => [
            'value' => $item['id'],
            'label' => $item['name'],
        ], $list);

        return $list;
    }

    public static function menuIds(int $id): array
    {
        $role = Role::select('menuIds')->find($id);

        if (!$role) {
            self::throwValidationException('id', ['角色不存在']);
        }

        return $role->menuIds ?? [];
    }


    public static function menus(int $id, array $meumIds): array
    {

        $role = Role::find($id);

        $role->update([
            'menuIds' => $meumIds
        ]);

        return [
            'id' => $role->id
        ];
    }

    public static function index(array $params): array
    {

        $query = Role::query()->orderBy('sort', 'asc');

        $pageNum = $params['pageNum'];
        $pageSize = $params['pageSize'];

        $paginator = $query->paginate($pageSize, ['code', 'createTime', 'dataScope', 'id', 'name', 'sort', 'status', 'updateTime'], 'page', $pageNum);

        $paginator->getCollection()->makeVisible(['createTime', 'updateTime']);

        return [
            'list'  => $paginator->items(),
            'total' => $paginator->total(),
        ];
    }


    public static function store(array $data): array
    {

        $role = Role::create($data);

        return [
            'id' => $role->id,
        ];
    }

    public static function show(string $id): array
    {

        $role = Role::select(['code', 'dataScope', 'id', 'name', 'sort', 'status'])->find($id);

        if (!$role) {
            self::throwValidationException('id', ['角色不存在']);
        }

        return $role->toArray();
    }


    public static function update(array $data, string $id): array
    {

        $role = Role::find($id);

        if (!$role) {
            self::throwValidationException('id', ['角色不存在']);
        }

        $role->update($data);

        return [
            'id' => $role->id,
        ];
    }

    public static function destroy(string $id): array
    {

        $role = Role::find($id);
        if (!$role) {
            self::throwValidationException('id', ['角色不存在']);
        }

        $role->delete();

        return [
            'id' => $role->id
        ];
    }
}
